package org.dht.com;

import java.util.LinkedList;
import java.util.List;

/**
 * The {@link Observable} class defines the basic methods for implementing the
 * observer pattern with the interface {@link Observer}
 * 
 * @param <E>
 */
public class Observable<E> {
	/**
	 * The list observers that observes this observable
	 */
	private List<Observer<E>> listeners;

	/**
	 * The constructor of the class. Creates an instance of the class
	 * {@link Observable}
	 */
	public Observable() {
		this.listeners = new LinkedList<Observer<E>>();
	}

	/**
	 * Add an observer to the list of observers
	 * 
	 * @param observer
	 *            The observer that will observes the observable
	 */
	public void addObserver(Observer<E> observer) {
		this.listeners.add(observer);
	}

	/**
	 * Remove an observer to the list of observers
	 * 
	 * @param observer
	 *            The observer that will observes the observable
	 */
	public void removeObserver(Observer<E> observer) {
		this.listeners.remove(observer);
	}

	/**
	 * Remove an observer of the list of observers
	 * 
	 * @param name
	 *            . The name of observer that will be removed
	 */
	public void removeObserver(String name) {
		for (Observer<E> observer : this.listeners) {
			if (observer.getName() != null && observer.getName().equals(name)) {
				this.listeners.remove(observer);
				break;
			}
		}
	}

	/**
	 * This method is used for notifying to the observers an event
	 * 
	 * @param e
	 *            The event that will be notified to the observers
	 */
	public void notifyMessage(E e) {
		for (Observer<E> listener : listeners) {
			listener.update(e);
		}
	}
}
